// 导入路由相关模块
import {createRouter, createWebHistory} from "vue-router";

// 定义路由信息
const routes = [{
    path: "/index",
    name: "index",
    component: () => import("../pages/Index.vue"),
    redirect: "/welcome",
    children:[{
        path: "/welcome",
        name: "welcome",
        component: () => import("../pages/Welcome.vue"),
    }, {
        path: "/index/user",
        name: "user",
        component: () => import("../pages/user/Index.vue"),
    }]
}, {
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue")
}, {
    path: "/",
    redirect: "/index",
}];

// 创建路由对象
const router = createRouter({
    history: createWebHistory(),
    routes
});

// 定义前置导航守卫和后置钩子
router.beforeEach((to, from, next) => {
    console.log("前置导航守卫");
    // 在之前导航守卫中判断是否已经登
    let token = window.sessionStorage.getItem("token");
    // 发送请求，判断token是否过期，如果过期就跳转到登录页
    if (token) {
        // 有token
        next();
    } else {
        // 如果没有token，但是访问路径是/login直接访问，如果不是强制跳转登录页面
        if (to.path === '/login') {
            next();
        } else {
            next({
                path: "/login"
            });
        }
    }
});

router.afterEach((to, from) => {
    console.log("后置钩子");
});

// 讲路由对象以默认模块导出
export default router;